<?php
/**
 * 导航内容Service
 * Date: 2025/09/10
 */

namespace App\Services\Admin;

use App\Models\CategoryModel;
use App\Models\ContentModel;
use App\Models\ViewModel;
use App\Services\BaseService;

class ContentService extends BaseService
{
    /**
     * 导航内容列表
     * @date 2025/09/15
     * @param array $params 请求参数
     * @return \Illuminate\Http\JsonResponse
     */
    public function list($params)
    {
        // 查询导航内容
        $data = ContentModel::query()
            ->select(['content.id', 'category.name as category_name', 'content.logo', 'content.title', 'content.sort', 'content.status', 'content.created_at'])
            ->leftJoin('category', 'category.id', 'content.category_id')
            ->when(isset($params['title']) && $params['title'] != '', function ($query) use ($params) {
                $query->where('content.title', 'like', '%' . $params['title'] . '%');
            })
            ->when(isset($params['category_id']) && !empty($params['category_id']), function ($query) use ($params) {
                $query->where('content.category_id', $params['category_id']);
            })
            ->when(isset($params['status']) && !empty($params['status']), function ($query) use ($params) {
                $query->where('content.status', $params['status']);
            })
            ->orderBy('content.sort', 'asc')
            ->orderBy('content.id', 'desc')
            ->paginate($params['size'] ?? config('project.size'));

        // 拼装列表其他数据
        $list = json_decode(json_encode($data->items()), true);
        if (!empty($list)) {
            $contentIds = array_column($list, 'id');
            $viewList = ViewModel::query()
                ->selectRaw('data_id, sum(pv) as view_count, count(distinct ip) AS ip_count')
                ->where('type', ViewModel::TYPE_CONTENT)
                ->whereIn('data_id', $contentIds)
                ->groupBy('data_id')
                ->get()
                ->toArray();
            $viewList = array_column($viewList, null, 'data_id');
            foreach ($list as &$item) {
                $item['view_count'] = $viewList[$item['id']]['view_count'] ?? 0;
                $item['ip_count'] = $viewList[$item['id']]['ip_count'] ?? 0;
            }
        }
        return $this->success([
            'list' => $list,
            'meta' => [
                'total' => $data->total(),
                'size'  => $data->perPage(),
                'page'  => $data->currentPage()
            ]
        ]);
    }

    /**
     * 导航内容创建
     * @date 2025/09/13
     * @param array $params 请求参数
     * @return \Illuminate\Http\JsonResponse
     */
    public function create($params)
    {
        // 分类判断
        $category = CategoryModel::query()->where('id', $params['category_id'])->first();
        if (empty($category)) {
            return $this->failed('分类不存在');
        }

        // 导航内容创建
        ContentModel::query()->create([
            'category_id' => $params['category_id'],
            'logo' => $params['logo'],
            'title' => $params['title'],
            'keywords' => $params['keywords'],
            'description' => $params['description'],
            'jump' => $params['jump'],
            'jump_link' => $params['jump_link'],
            'sort' => $params['sort'],
            'status' => $params['status']
        ]);
        return $this->success();
    }

    /**
     * 导航内容详情
     * @date 2025/09/15
     * @param int $id 导航内容ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id)
    {
        // 导航内容详情
        $contentInfo = ContentModel::query()
            ->select([
                'content.id',
                'content.category_id',
                'category.name as category_name',
                'content.logo',
                'content.title',
                'content.keywords',
                'content.description',
                'content.jump',
                'content.jump_link',
                'content.sort',
                'content.status'
            ])
            ->leftJoin('category', 'category.id', 'content.category_id')
            ->where('content.id', $id)
            ->first();
        if (empty($contentInfo)) {
            return $this->failed('导航不存在');
        }
        return $this->success($contentInfo);
    }

    /**
     * 导航内容更新
     * @date 2025/09/15
     * @param array $params 请求参数
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($params)
    {
        // 检测导航内容
        if (!ContentModel::query()->where('id', $params['id'])->exists()) {
            return $this->failed('导航不存在');
        }

        // 导航内容更新
        ContentModel::query()->where('id', $params['id'])->update([
            'category_id' => $params['category_id'],
            'logo' => $params['logo'],
            'title' => $params['title'],
            'keywords' => $params['keywords'],
            'description' => $params['description'],
            'jump' => $params['jump'],
            'jump_link' => $params['jump_link'],
            'sort' => $params['sort'],
            'status' => $params['status']
        ]);
        return $this->success();
    }

    /**
     * 导航内容删除
     * @date 2025/09/15
     * @param int $id 导航内容ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete($id)
    {
        // 检测导航内容
        if (!ContentModel::query()->where('id', $id)->exists()) {
            return $this->failed('导航不存在');
        }

        // 导航内容删除
        ContentModel::query()->where('id', $id)->delete();
        return $this->success();
    }
}
